package com.ctgu.demo02.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.demo02.entity.BooksEntity;
import com.ctgu.demo02.service.BooksService;
import com.ctgu.demo02.mapper.BooksMapper;
import com.ctgu.demo02.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
* @author Alex2
* @description 针对表【t_books】的数据库操作Service实现
* @createDate 2025-03-11 17:46:50
*/
@Service
public class BooksServiceImpl extends ServiceImpl<BooksMapper, BooksEntity>
    implements BooksService {

    @Autowired
    private BooksMapper booksMapper;

    @Override
    public ApiResult insertBooks(String name) {
        BooksEntity book = lambdaQuery().eq(BooksEntity::getName, name).one();
        if (book != null) {
            return ApiResult.error("该书籍已存在，新增失败");
        }
        BooksEntity booksEntity = new BooksEntity(null, name, null);
        boolean save = save(booksEntity);
        if (!save) {
            return ApiResult.error("新增书籍失败");
        }
        return ApiResult.success("新增书籍成功");
    }

    @Override
    public ApiResult deleteBookById(Integer id) {
        int i = booksMapper.deleteById(id);// 删除时，MyBatis-Plus 会自动更新 is_delete = 1
        if (i > 0) {
            return ApiResult.success("删除成功");
        } else {
            return ApiResult.error("删除失败");
        }
    }

    @Override
    public ApiResult getAllUnDelete() {
        List<BooksEntity> booksEntities = booksMapper.selectList(null);// 查询时，MyBatis-Plus 会自动加上 is_delete = 0
        if (booksEntities.isEmpty()) {
            return ApiResult.success("获取列表为空", Collections.emptyList());
        }
        return ApiResult.success("获取列表成功", booksEntities);
    }
}